<?php

class Admin_Model_GalleryItemMapper {
	protected $_dbTable;
	protected $_mapperSize;
	protected $_sizes;
	
	public function getSizes(){
		if ($this->_sizes==null)
			$this->_sizes = $this->getSizesMapper()->fetchAll();
		return $this->_sizes;
	}
	
	public function getSizesMapper(){
		if ($this->_mapperSize==null)
			$this->_mapperSize = new Admin_Model_GallerySizesMapper();
		return $this->_mapperSize;
	}
	
	public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_GalleryItem');
        }
        return $this->_dbTable;
    }
    
    /**
     * Поиск по идентификаторам картинки. 
     * Если установлен идентификатор размера, то вернет одну картинку.
     * Если идентификатор размера не установлен, вернет массив картинок
     * всех возможных размеров для изображения с идентификаторов $id
     * @param (array|int) $id - идентификатор изображения
     * @param int $sizeId - идентификатор размера превью.
     * @return mixed
     */
    public function find($id,$sizeId = null){
    	$t = $this->getDbTable();
    	if ($sizeId!=null){
    		$rowset = $t->find($id,$sizeId);
    		$row = $rowset->current();
    		return is_null($row)? null: new Admin_Model_GalleryItem($row->toArray());
    	}
    	else{
    		$rowset = $t->fetchAll($t->select()->where('Id=?',$id));
    		$result = new Admin_Model_Image();
    		foreach($rowset as $row){
    			$result->Items[] = new Admin_Model_GalleryItem($row->toArray());
    		}
    		return $result;
    	}
    }
    
    public function findAllImageSizes($id){
    	$t1 = $this->getDbTable();
    	$t2 = new Admin_Model_DbTable_GallerySizes();
    	$tableName1 = $t1->info(Zend_Db_Table_Abstract::NAME);
    	$tableName2 = $t2->info(Zend_Db_Table_Abstract::NAME);
    	$set = $t1->fetchAll($t1->select()->setIntegrityCheck(false)
    			->from(array('t1'=>$tableName1),Zend_Db_Select::SQL_WILDCARD)
    			->join(array('t2'=>$tableName2), 't1.SizeId=t2.Id','Name as SizeName')
    			->where('t1.Id = ?',$id));
    	$result = array();
    	foreach($set as $r){
    		
    		$gi = new Admin_Model_GalleryItemAndSize($r->toArray());
    		$gi->CompositeId = $gi->getId().'-'.$gi->getSizeId();
    		
    		$result[] = $gi;
    	}
    	return $result;
    }
    
    public function save(Admin_Model_GalleryItem $item, $forceInsert = false, $onlyFields = false){
    	$data = $item->toArray($onlyFields);
        if (null === ($id = $item->getId())) {
            unset($data['Id']);
            return $this->getDbTable()->insert($data);
        }
        elseif ($forceInsert){
        	return $this->getDbTable()->insert($data);
        }
        else {
            $this->getDbTable()->update($data, array('Id = ?' => $id, 'SizeId = ?'=>$item->getSizeId()));
            return 0;
        }
    }
    
    public function delete($id, $sizeId = null, $fromDB = true, $fromDisk = false){
    	$num = 0;
    	$IDs = is_array($id)? $id: array($id);
    	foreach($IDs as $i){
	    	if ($fromDB){
	    		$where = array("Id={$i}");
	    		if (!is_null($sizeId)) $where[]="SizeId={$sizeId}";
	    		$num += $this->getDbTable()->delete($where);
	    	}
	    	 
	    	if ($fromDisk && (($fromDB && ($num>0)) || !$fromDB))
	    	{
	    		$d = dir(Admin_Model_GalleryItem::getPath());
	    		$mask = $i.'_';
	    		$mask .= $sizeId!=null?$sizeId.'_':''; 
	    		
				while (false !== ($entry = $d->read())) {
					if (strpos($entry,$mask)===0){
						unlink(Admin_Model_GalleryItem::getPath().$entry);
					}
				}
				$d->close();
	    	}
    	}
    }
    /*
     * Клонирует картику со всеми её вариантами размера
     * Возвращает массив вариантов (массив Admin_Model_GalleryItem)
     */
    public function cloneImage($id){
    	$t  = $this->getDbTable();
    	$rowset = $t->fetchAll("Id=".$id);
    	$row = $rowset->current();
    	$id = null;
    	$items = array();
    	foreach($rowset as $row){
    		$data = $row->toArray();
    		$oldId = $data['Id'];
    		unset($data['Id']);
    		if ($id==null){
    			$id = $this->getDbTable()->insert($data);
    			$data['Id'] = $id['Id'];
    		}
    		else{
    			$data['Id'] = $id['Id'];
    			$this->getDbTable()->insert($data);
    		}
    		copy(Admin_Model_GalleryItem::getPath().$oldId.'_'.$data['SizeId'].'_'.$data['Width'].'x'.$data['Height'].'.'.$data['Ext'],
    			Admin_Model_GalleryItem::getPath().$data['Id'].'_'.$data['SizeId'].'_'.$data['Width'].'x'.$data['Height'].'.'.$data['Ext']
    			);
    		$items[] = new Admin_Model_GalleryItem($data);
    	}
        return $items;
        /*$result = new Admin_Model_Image();
        $result->Items = $items;
        $result->ThumbID = $thumbID;
    	return $result;*/
    }

	public function addThumbnailFromFile($galleryItem, $sizeId, $alt, $title, $src, $resize = false){
		if (!file_exists($src)) throw new Exception('File not exists');
		$info = pathinfo($src);
		list($width, $height) = getimagesize($src);
		if (is_null($width) || is_null($height)) 
			throw new Exception('file: '.$src.' cannot be processed');
		$gi = new Admin_Model_GalleryItem();
     	$gi	->setId($galleryItem->getId())
			->setSizeId($sizeId)
     		->setAlt($alt)
     		->setTitle($title)
     		->setWidth($width)
     		->setHeight($height)
     		->setExt($info['extension'])
     		->setOrder(0);
		$newId = $this->save($gi,true);
		if ($resize){
			throw new Exception('Эта ветка не реализована');
		}
		else{
			copy($src, Admin_Model_GalleryItem::getPath()."{$gi->getId()}_{$sizeId}_{$width}x{$height}.{$info['extension']}");
		}
		return $gi;
	}
	
	public function createFrom($src, $alt, $title,$createAllSizes=true){
		if (!file_exists($src)) throw new Exception('File not exists:'.$src);
		$info = pathinfo($src);
		$this->getSizes();
		list($width, $height) = getimagesize($src);
		if (is_null($width) || is_null($height)) throw new Exception('file: '.$src.' cannot be processed');
     	$gi = new Admin_Model_GalleryItem();
     	$gi->setSizeId($this->_sizes[0]->getId())
     		->setAlt($alt)
     		->setTitle($title)
     		->setWidth($width)
     		->setHeight($height)
     		->setExt($info['extension'])
     		->setOrder(0);
     	
     	$newId = $this->save($gi);
     	$gi->setId($newId['Id']);
     	$result = new Admin_Model_Image();
     	$result->Items[]=$gi;
     	
		if (!$createAllSizes) return $result;
     	
     	foreach($this->_sizes as $size){
     		if (($size->getWidth()>0) && ($size->getHeight()>0)){ 
     			list($width,$height) = Nippy_Image::ResizeImage($src, 
     										$info['extension'], 
     										$size->getWidth(), 
     										$size->getHeight(),
     										Admin_Model_GalleryItem::getPath().$newId['Id'].'_'.$size->getId().'_%wx%h.'.$info['extension']
     										);
     			$gi1 = new Admin_Model_GalleryItem($gi->toArray());
     			$gi1->setSizeId($size->getId())
     				->setWidth($width)
     				->setHeight($height);
     			$this->save($gi1, true);
     			$result->Items[]=$gi1;
     		}
     		else
     			copy($src, Admin_Model_GalleryItem::getPath()."{$newId['Id']}_{$size->getId()}_{$width}x{$height}.{$info['extension']}");
     	}
     	return $result;
	}
}

?>